using AutoMapper;
using MediatR;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.ERP.MaterialFile
{
    /// <summary>
    /// 删除物料分类处理类（逻辑删除）
    /// </summary>
    public class DeleteMaterTypeHandler : IRequestHandler<DeleteMaterTypeCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<MaterType> materTypeRepository;
        private readonly ILogger<DeleteMaterTypeHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materTypeRepository">物料分类仓储</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="mapper">对象映射器</param>
        public DeleteMaterTypeHandler(
            IBaseRepository<MaterType> materTypeRepository,
            ILogger<DeleteMaterTypeHandler> logger,
            IMapper mapper)
        {
            this.materTypeRepository = materTypeRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理删除物料分类请求
        /// </summary>
        /// <param name="request">删除物料分类请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<APIResult<bool>> Handle(DeleteMaterTypeCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();

            try
            {
                logger.LogInformation("开始删除物料分类，ID: {Id}", request.Id);

                // 1. 验证分类ID
                if (request.Id <= 0)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类ID无效";
                    logger.LogWarning("分类ID验证失败: {Id}", request.Id);
                    return result;
                }

                // 2. 检查分类是否存在
                var materTypeExists = materTypeRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM MaterType WHERE Id = @Id AND IsDeleted = false",
                    new { Id = request.Id });

                if (materTypeExists == 0)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "指定的物料分类不存在或已被删除";
                    logger.LogWarning("物料分类不存在或已删除: {Id}", request.Id);
                    return result;
                }

                // 3. 检查是否有子分类
                var hasChildren = materTypeRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM MaterType WHERE ParentId = @ParentId AND IsDeleted = false",
                    new { ParentId = request.Id });

                if (hasChildren > 0)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "该分类下存在子分类，无法删除";
                    logger.LogWarning("存在子分类，删除失败: {Id}, 子分类数量: {Count}", request.Id, hasChildren);
                    return result;
                }

                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        // 4. 执行逻辑删除（更新IsDeleted字段为true）
                        var sql = @"UPDATE MaterType 
                                   SET IsDeleted = true
                                   WHERE Id = @Id AND IsDeleted = false";

                        var parameters = new
                        {
                            Id = request.Id
                        };

                        var affectedRows = materTypeRepository.Execute(sql, parameters);

                        if (affectedRows <= 0)
                        {
                            throw new InvalidOperationException("物料分类删除失败，未影响任何记录");
                        }

                        tran.Complete();

                        result.Code = APIEnums.Success;
                        result.Data = true;
                        result.Msg = "物料分类删除成功";

                        logger.LogInformation("物料分类 {Id} 删除成功", request.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "删除物料分类过程中发生错误: {Message}", ex.Message);
                        result.Code = APIEnums.Error;
                        result.Msg = "删除物料分类失败";
                        result.Data = false;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除物料分类失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "删除物料分类失败";
                result.Data = false;
            }

            return result;
        }
    }
}